import sys
import os

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + '../')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'riscv_build_dataset.settings')

import django
from tqdm import tqdm

django.setup()

from fedora.models import koji_package, koji_build
from obs.models import obs_project, obs_package, obs_job_history, obs_package_build_log
from obs.mongo_log import OBSLog

obs_project_name = [
    'openEuler:22.03',
    'openEuler:22.09',
    'openEuler:23.03',
    'openEuler:23.09:RISC-V',
    'openEuler:Mainline:RISC-V',
]

o = OBSLog()

print('--- OBS Statistics ---')
for project_name in obs_project_name:
    print()
    print(project_name)
    project = obs_project.objects.get(project_name=project_name)

    packages = obs_package.objects.filter(project=project)
    print('Packages:', packages.count())

    jobs = obs_job_history.objects.filter(project=project)
    success_jobs = jobs.filter(build_status_code='succeeded')
    failed_jobs = jobs.filter(build_status_code='failed')
    print('Jobs:', jobs.count(), 'success jobs:', success_jobs.count(), 'failed jobs:', failed_jobs.count())

    logs = obs_package_build_log.objects.filter(project=project)
    success_logs = logs.filter(status='succeeded')
    failed_logs = logs.filter(status='failed')
    unknown_logs = logs.filter(status='unknown')
    print('Logs:', logs.count(),
          'success logs:', success_logs.count(),
          'failed logs:', failed_logs.count(),
          'unknown logs:', unknown_logs.count())

    # logs_mongo = o.get_log_by_project_id(project.project_id)
    # print('Logs in MongoDB:', logs_mongo.count())

print('\n\n--- Koji Statistics ---')
packages = koji_package.objects.all()
print('Packages:', packages.count())

builds = koji_build.objects.all()
success_builds = builds.filter(state=1)
failed_builds = builds.filter(state=3)
canceled_builds = builds.filter(state=4)
print('Total builds:', builds.count(),
      'Success builds:', success_builds.count(),
      'Failed builds:', failed_builds.count(),
      'Canceled builds:', canceled_builds.count())

tags = ['fc37', 'fc38', 'fc39', 'fc40']
for tag in tags:
    builds = koji_build.objects.filter(tag=tag)
    print(f'Tag: {tag}, Build count: {builds.count()}')
